package Hash;

import java.util.HashMap;

public class Test {
    //实现哈希随机
    public static class Pool<K>{
        private HashMap<K,Integer> keyIndexMap;
        private HashMap<Integer,K> indexKeyMap;
        private int size;


        public Pool(){
            this.keyIndexMap = new HashMap<>();
            this.indexKeyMap = new HashMap<>();
            this.size = 0;
        }
        public void insert(K key){
            if (!keyIndexMap.containsKey(key)){
                this.keyIndexMap.put(key,size);
                this.indexKeyMap.put(size++,key);
            }
        }
        public void delete(K key){
            if (keyIndexMap.containsKey(key)){
                //记录位置,然后堵洞
                int deleteIndex = keyIndexMap.get(key);
                //将最后一个位置拿出来
                int lastIndex = --size;
                K lastKey = indexKeyMap.get(lastIndex);
                //堵洞交换
                keyIndexMap.put(lastKey,deleteIndex);
                indexKeyMap.put(deleteIndex,lastKey);
                keyIndexMap.remove(key);
                indexKeyMap.remove(lastIndex);
            }
        }
        public K getRondom(){
            if (size == 0)return null;
            int randomIndex =(int) (Math.random()*size);//0 ~ size -1
            return indexKeyMap.get(randomIndex);
        }
    }
}
